<template>
  <!-- 新增活动 -->
  <el-dialog
    v-model="visible"
    :title="form.shopCouponId ? (visitDetail ? '查看优惠券' : '修改优惠券') : '新增优惠券'"
    class="addCoupon"
    width="900px"
    center
    top="10vh"
    :close-on-click-modal="false"
    @close="close"
  >
    <div class="addCouponBox">
      <el-form
        ref="ruleFormRef"
        class="formBox"
        :model="form"
        :rules="rules"
        label-width="150px"
        :disabled="visitDetail"
      >
        <el-form-item label="优惠券类型">
          <el-radio v-model="form.couponType" :label="1">满减券</el-radio>
          <el-radio v-model="form.couponType" :label="2">折扣券</el-radio>
        </el-form-item>
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input
            v-model="form.couponName"
            maxlength="20"
            placeholder="请输入优惠券名称"
            onblur="value=value.replace(/(^\s*)|(\s*$)/g, '')"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            maxlength="200"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item class="applyType" label="适用商品" prop="applyType">
          <el-radio v-model="form.applyType" :label="1">全部商品</el-radio>
          <el-radio
            v-model="form.applyType"
            :label="2"
            @change="chooseProduct(2)"
          >指定商品可用</el-radio>
          <span
            v-if="!visitDetail"
            class="selectBtn"
            @click="chooseProduct(2)"
          >
            请选择
            <i
              v-if="form.applyType === 2 && idList.length !== 0"
              class="selectNum"
            >
              {{ idList.length }}
            </i>
          </span>
          <span
            v-if="visitDetail && form.applyType === 2"
            class="selectBtn"
            @click="chooseProduct(2)"
          >
            查看商品
            <i
              v-if="form.applyType === 2 && idList.length !== 0"
              class="selectNum"
            >
              {{ idList.length }}
            </i>
          </span>
          <el-radio
            v-model="form.applyType"
            :label="3"
            @change="chooseProduct(3)"
          >指定商品不可用</el-radio>
          <span
            v-if="!visitDetail"
            class="selectBtn"
            @click="chooseProduct(3)"
          >
            请选择
            <i
              v-if="form.applyType === 3 && idList.length !== 0"
              class="selectNum"
            >
              {{ idList.length }}
            </i>
          </span>
          <span
            v-if="visitDetail && form.applyType === 3"
            class="selectBtn"
            @click="chooseProduct(3)"
          >
            查看商品
            <i
              v-if="form.applyType === 3 && idList.length !== 0"
              class="selectNum"
            >
              {{ idList.length }}
            </i>
          </span>
        </el-form-item>
        <el-form-item class="inputW" label="使用门槛" prop="threshold">
          <!-- 订单满<el-input v-model="form.threshold" :disabled="isThreshold" type="number" oninput="value=value.replace(/-/, '')" />元 -->
          订单满
          <el-input-number
            v-model="form.threshold"
            :disabled="isThreshold"
            :controls="false"
            :max="999999999"
            :min="0"
            :precision="2"
            :step="0.01"
            style="margin: 0 8px;"
          />
          元
          <el-checkbox
            v-model="isThreshold"
            @change="changeThreshold"
          >无门槛</el-checkbox>
        </el-form-item>
        <el-form-item
          v-if="form.couponType === 1"
          class="inputW"
          label="优惠内容"
          prop="couponContent"
        >
          <!-- 减<el-input v-model="form.couponContent" type="number" />元 -->
          减
          <el-input-number
            v-model="form.couponContent"
            :controls="false"
            :max="999999999"
            :min="0"
            :precision="2"
            :step="0.01"
            style="margin: 0 8px;"
          />
          元
        </el-form-item>
        <el-form-item
          v-else
          class="inputW discount"
          label="优惠内容"
          prop="couponContent"
        >
          <!-- 打<el-input v-model="form.couponContent" type="number" />折 -->
          打
          <el-input-number
            v-model="form.couponContent"
            :controls="false"
            :min="0.1"
            :max="9.9"
            :precision="1"
            :step="0.1"
          />
          折
          <label>输入值要大于0 小于10，可保留一位小数</label>
        </el-form-item>
        <el-form-item class="timeDataBox" label="用券时间">
          <el-radio v-model="form.timeType" :label="1">固定时间</el-radio>
          <div class="dateBox">
            <el-form-item>
              <el-date-picker
                v-model="fixedTimeData"
                :disabled="form.timeType === 2"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item class="boxWidth">
          <el-radio v-model="form.timeType" :label="2">领券当日起</el-radio>
          <el-input
            v-model="form.effectiveDay"
            maxlength="9"
            :disabled="form.timeType !== 2"
            oninput="value=value.replace(/[^\d]/g,'')"
          />天内可用
        </el-form-item>
        <el-form-item class="boxWidth" label="发放数量" prop="number">
          <el-input
            v-model="form.number"
            maxlength="9"
            oninput="value=value.replace(/[^\d]/g,'')"
          />张
        </el-form-item>
        <el-form-item class="boxWidth" label="每人限领次数">
          <el-radio v-model="form.receiveType" :label="1">无限制</el-radio>
          <el-radio v-model="form.receiveType" :label="2">限制</el-radio>
          <el-input
            v-model="form.frequency"
            maxlength="9"
            :disabled="form.receiveType === 1"
            oninput="value=value.replace(/[^\d]/g,'')"
          />次
        </el-form-item>
        <el-form-item label="叠加平台优惠">
          <el-radio-group v-model="form.ifAdd">
            <el-radio :label="0">不叠加</el-radio>
            <el-radio :label="1">叠加</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button
        v-show="!visitDetail"
        type="primary"
        @click="addCouponFn"
      >保 存</el-button>
      <el-button
        v-if="visitDetail"
        type="primary"
        @click="goToCoupon"
      >取 消</el-button>
      <el-button v-else @click="goToCoupon">取 消</el-button>
    </span>
    <!-- 新建分组弹框 -->
    <el-dialog
      v-model="groupVisible"
      :title="visitDetail ? '查看商品' : '选择商品'"
      width="70%"
      top="50px"
      class="group-dialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
    >
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          ref="multipleTableRef"
          :data="groupData"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          row-key="productId"
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            v-if="!visitDetail"
            type="selection"
            :reserve-selection="true"
            width="55"
          />
          <el-table-column label="产品主图" width="220" align="center">
            <template #default="scope">
              <img height="80" width="80" :src="scope.row.image" alt srcset />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="产品名称" width="220" />
          <el-table-column
            prop="productId"
            label="产品id"
            show-overflow-tooltip
          />
          <!--          <el-table-column prop="discountPrice" label="售价（元）" show-overflow-tooltip />-->
          <el-table-column
            prop="originalPrice"
            label="原价（元）"
            show-overflow-tooltip
          />
          <el-table-column
            prop="stockNumber"
            label="库存（件）"
            show-overflow-tooltip
          />
          <!--          <el-table-column prop="volume" label="销量" show-overflow-tooltip />-->
        </el-table>
        <div class="fenye">
          <el-pagination
            :current-page="groupQuery.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="groupQuery.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <div class="footBtnBox">
          <span class="dialog-footer">
            <el-button
              v-if="!visitDetail"
              type="primary"
              @click="saveIdList"
            >确 定</el-button>
            <el-button @click="closeSelect">取 消</el-button>
          </span>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { defineComponent, ref, shallowRef } from 'vue'
import {
  addCoupon,
  getProducts,
  couponDetail,
  updateCoupon,
} from '@/api/marketing'

defineComponent({
  name: 'CouponForm'
})

const emit = defineEmits(['reset'])

defineExpose({
  open, close
})

function initCouponForm () {
  return {
    type: 1,
    applyType: 1, //  适用商品 1-全部商品 2-指定商品可用 3-指定商品不可用
    couponContent: null, // 优惠内容减多少元
    couponName: '', //  优惠券名称
    couponType: 1, //  优惠券类型 1-满减券 2-折扣券
    effectiveDay: null, //  领券当日几天内（天数）
    effectiveStart: '', //  用券开始时间
    effectiveEnd: '', //  用券结束时间
    frequency: null, //  限制次数
    ids: [], //  选中的商品id数组
    excludeIds: [], // 排除的商品id数组
    ifAdd: 0, //  是否叠加平台优惠 1-是 0-否
    number: null, //  发放数量
    receiveType: 1, //  每人限领次数 1-无限次 2-限制几次
    remark: '', //  备注
    shopCouponId: null, //  店铺优惠券id
    threshold: 0, //  使用门槛满多少元，无门槛为0
    timeType: 1, //  用券时间 1-固定时间 2-领券当日起几天内可用
  }
}
const visible = ref(false)
const groupVisible = ref(false)
const visitDetail = ref(false)
const form = ref(initCouponForm())
// 优惠券使用的固定时间
const fixedTimeData = ref([])
// 优惠券是否无门槛
const isThreshold = shallowRef(true)
const currentType = shallowRef(1)
const ruleFormRef = ref()
const multipleTableRef = ref()
const groupQuery = ref({
  activityId: null,
  queryType: null,
  page: 1,
  pageSize: 10
})
const total = ref(0)
const groupData = ref([])
const multipleSelection = ref([])
// 选中的id
const idList = ref([])

const rules = {
  couponName: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
  ],
  couponContent: [{ required: true, message: '请输入优惠金额' }],
  number: [
    { required: true, message: '请输入发放数量', trigger: 'blur' },
  ],
}

function open (id, isDetail) {
  form.value.shopCouponId = id
  visitDetail.value = isDetail
  if (id) {
    getCouponInfo()
  }
  visible.value = true
}
function close () {
  visible.value = false
  form.value = initCouponForm()
  groupQuery.value.page = 1
  fixedTimeData.value = []
  idList.value = []
  multipleTableRef.value?.clearSelection()
  ruleFormRef.value?.resetFields()
}

function addCouponFn () {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (form.value.timeType === 1 && fixedTimeData.value.length === 0) {
        ElMessage({
          message: '请选择用券时间开始和结束日期',
          type: 'warning',
        })
        return false
      }
      if (
        form.value.timeType === 2 &&
            form.value.effectiveDay === null
      ) {
        ElMessage({
          message: '请填写领券多久内可以使用时间',
          type: 'warning',
        })
        return false
      }
      if (
        form.value.receiveType === 2 &&
            form.value.frequency === null
      ) {
        ElMessage({
          message: '请填写每人限领次数',
          type: 'warning',
        })
        return false
      }
      if (form.value.couponType === 2) {
        var regExp = /^([1-9]{1})(.\d{1})?$/
        if (!regExp.test(form.value.couponContent)) {
          ElMessage({
            message: '格式输入不正确',
            type: 'warning',
          })
          return false
        }
      }
      if ([2, 3].includes(parseInt(form.value.applyType))) {
        if (
          !form.value.ids ||
              !form.value.ids.length ||
              form.value.ids.length === 0
        ) {
          ElMessage({
            message: '请选择指定商品',
            type: 'warning',
          })
          return false
        }
      }
      form.value.effectiveStart = fixedTimeData.value[0]
      form.value.effectiveEnd = fixedTimeData.value[1]
      if (form.value.shopCouponId) {
        updateCoupon(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('修改成功')
            form.value = initCouponForm()
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      } else {
        addCoupon(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('提交成功')
            form.value = initCouponForm()
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      }
    } else {
      return false
    }
  })
}

// 选择商品
function chooseProduct (type) {
  groupVisible.value = true
  if (currentType.value !== type) {
    idList.value = []
    if (multipleSelection.value.length !== 0) {
      multipleTableRef.value.clearSelection()
    }
  }
  currentType.value = type
  if (visitDetail.value) {
    groupQuery.value.activityId = form.value.shopCouponId
    groupQuery.value.queryType = form.value.applyType
  } else {
    groupQuery.value.activityId = null
    groupQuery.value.queryType = null
  }
  getProList()
}

function getProList () {
  getProducts(groupQuery.value).then((res) => {
    if (res.code === '') {
      groupData.value = res.data.list
      total.value = res.data.total
      // 点击编辑时回显表格勾选
      if (form.value.shopCouponId) {
        for (let i = 0; i < groupData.value.length; i++) {
          if (idList.value.includes(groupData.value[i].productId)) {
            multipleTableRef.value.toggleRowSelection(groupData.value[i])
          }
        }
      }
    }
  })
}
function handleSizeChange (val) {
  groupQuery.value.pageSize = val
  getProList()
}
function handleCurrentChange (val) {
  groupQuery.value.page = val
  getProList()
}

// 选中商品
function handleSelectionChange (val) {
  multipleSelection.value = val
}
// 保存选择商品ID
function saveIdList () {
  idList.value = []
  multipleSelection.value.forEach((i) => {
    idList.value.push(i.productId)
  })
  form.value.ids = idList.value
  form.value.applyType = currentType.value
  groupVisible.value = false
}
// 取消选择
function closeSelect () {
  groupVisible.value = false
}
// 跳转优惠券列表
function goToCoupon () {
  emit('reset')
}
function getCouponInfo () {
  couponDetail({ shopCouponId: form.value.shopCouponId }).then(res => {
    form.value = Object.assign(form.value, res.data)
    fixedTimeData.value = [form.value.effectiveStart, form.value.effectiveEnd]
    if (form.value.applyType === 2) {
      form.value.products.forEach((item) => {
        idList.value.push(item.productId)
      })
    } else if (form.value.applyType === 3) {
      form.value.excludeIds.forEach((item) => {
        idList.value.push(item)
      })
    } else {
      idList.value = []
    }
    currentType.value = res.data.applyType
  })
}
function changeThreshold (val) {
  // 输入框值改变
  if (val) {
    form.value.threshold = 0
  }
}

function proving1 (e) {
  var keynum = window.event ? e.keyCode : e.which // 获取键盘码
  // var keychar = String.fromCharCode(keynum) // 获取键盘码对应的字符
  if (
    e.key
      .replace(/[^\d^\.]+/g, '')
      .replace('.', '$#$')
      .replace(/\./g, '')
      .replace('$#$', '.') === '' &&
        keynum !== 8
  ) {
    ElMessage.warning('禁止输入中文或空')
    e.target.value = ' '
  }
}

</script>

<style lang="scss" scoped>
.addCoupon {
  background: #ffffff;
  .dialog-footer {
    display: flex;
    justify-content: center;
    .el-button {
      margin: 0px 16px;
    }
  }
  .formBox {
    .flexBox {
      display: flex;
    }
    .applyType {
      span {
        width: 100px;
        height: 30px;
        line-height: 30px;
        background: #66b1ff;
        color: #ffffff;
        text-align: center;
        display: inline-block;
        font-size: 14px;
        margin-right: 30px;
        border-radius: 4px;
        cursor: pointer;
        position: relative;
        i {
          position: absolute;
          right: -10px;
          top: -10px;
          width: 25px;
          height: 25px;
          line-height: 25px;
          background: #ffffff;
          border-radius: 50%;
          border: 1px solid #66b1ff;
          text-align: center;
          color: #3A68F2;
          font-style: normal;
          font-size: 12px;
        }
      }
    }
  }
  .footBtnBox {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 50px;
  }
  .dateBox {
    display: flex;
    align-items: center;
    .description {
      width: 59px;
      text-align: center;
      display: block;
      font-size: 14px;
      color: #999999;
    }
  }
  .discount label {
    color: #cccccc;
    font-weight: 500;
    padding-left: 30px;
  }
}
</style>

<style scoped>
:deep(.flexBox) .el-input {
  width: 300px;
}
:deep(.inputW) .el-input,
.el-input-number {
  width: 100px;
  /* margin: 0 8px; */
}
:deep(.inputW) .el-input .el-input__inner {
  text-align: center;
}
:deep(.inputW) .el-form-item__error {
  padding-left: 25px;
}
:deep(.inputW) .el-checkbox {
  margin-left: 20px;
}
:deep(.inputW) .el-radio {
  margin-left: 30px;
}
:deep(.boxWidth) .el-input {
  width: 100px;
  margin-right: 15px;
}
:deep(.boxWidth) .el-input .el-input__inner {
  text-align: center;
}
:deep(.addCoupon) .el-button--primary {
  background: #3A68F2;
  border-color: #3A68F2;
}
:deep(.addCoupon) .el-dialog__header {
  background-color: #3A68F2;
}
:deep(.addCoupon) .el-dialog__headerbtn .el-dialog__close {
  color: #ffffff;
}
:deep(.addCoupon) .timeDataBox .el-form-item__content {
  display: flex;
  align-items: center;
}
:deep(.addCoupon) .timeDataBox .el-form-item__label {
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type='number'] {
  -moz-appearance: textfield;
}
</style>
